<template>
  <view class="order-confirm-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">确认订单</text>
    </view>
    
    <!-- 收货地址 -->
    <view class="address-section" @click="goToAddressList">
      <view class="address-content" v-if="selectedAddress">
        <view class="address-info">
          <view class="address-name-phone">
            <text class="name">{{selectedAddress.name}}</text>
            <text class="phone">{{selectedAddress.phone}}</text>
          </view>
          <view class="address-detail">
            <text>{{selectedAddress.city}} {{selectedAddress.department}} {{selectedAddress.houseNumber}}</text>
          </view>
        </view>
        <uni-icons type="right" size="20" color="#999"></uni-icons>
      </view>
      <view class="no-address" v-else>
        <text>请选择收货地址</text>
        <uni-icons type="right" size="20" color="#999"></uni-icons>
      </view>
    </view>
    
    <!-- 店铺信息 -->
    <view class="shop-section">
      <view class="shop-info">
        <image :src="shopInfo.imgUrl" mode="aspectFill"></image>
        <text class="shop-name">{{shopInfo.name}}</text>
      </view>
      
      <!-- 商品列表 -->
      <view class="product-list">
        <view class="product-item" v-for="(product, index) in productList" :key="product._id">
          <image :src="product.imgUrl" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{product.name}} {{product.weight || ''}}</text>
            <view class="product-price-count">
              <text class="price">¥{{product.price}}</text>
              <text class="count">x{{product.count}}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 配送费 -->
      <view class="delivery-section">
        <text>配送费</text>
        <text>¥{{shopInfo.expressPrice || 0}}</text>
      </view>
    </view>
    
    <!-- 订单备注 -->
    <view class="remark-section">
      <text>订单备注</text>
      <input type="text" placeholder="请输入备注信息" v-model="remark" />
    </view>
    
    <!-- 底部状态栏 -->
    <view class="footer">
      <view class="total-price">
        <text>实付金额：</text>
        <text class="price">¥{{totalPrice.toFixed(2)}}</text>
      </view>
      <view class="submit-btn" @click="submitOrder">
        <text>提交订单</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopInfo: {},
      productList: [],
      selectedAddress: null,
      addressList: [],
      remark: '',
      totalPrice: 0,
      cartProducts: {} // 添加购物车数据
    }
  },
  onLoad(options) {
    // 从本地存储获取购物车数据和店铺信息
    const cartData = uni.getStorageSync('cartData');
    const shopInfo = uni.getStorageSync('shopInfo');
    const cartProductsInfo = uni.getStorageSync('cartProductsInfo') || '{}';
    
    if (shopInfo) {
      this.shopInfo = JSON.parse(shopInfo);
    }
    
    // 获取地址列表
    this.loadAddressList();
    
    // 获取商品详情
    if (cartData && cartProductsInfo) {
      this.cartProducts = JSON.parse(cartData);
      const productsInfo = JSON.parse(cartProductsInfo);
      
      // 构建商品列表
      this.productList = [];
      let total = 0;
      
      // 只处理当前超市的商品
      const shopId = this.shopInfo._id;
      
      for (const id in this.cartProducts) {
        // 检查是否是当前超市的商品
        if (id.startsWith(`${shopId}_`)) {
          const product = productsInfo[id];
          if (product) {
            const count = this.cartProducts[id];
            this.productList.push({
              _id: product._id,
              name: product.name,
              imgUrl: product.imgUrl,
              price: product.price,
              weight: product.weight,
              count: count
            });
            
            total += product.price * count;
          }
        }
      }
      
      // 加上配送费
      if (this.shopInfo.expressPrice) {
        total += parseFloat(this.shopInfo.expressPrice);
      }
      
      this.totalPrice = total;
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    loadAddressList() {
      // 直接从服务器获取最新的地址列表，不使用本地存储
      uni.request({
        url: 'http://localhost:3000/address',
        success: (res) => {
          if (res.statusCode === 200) {
            // 确保地址列表没有重复项
            const uniqueAddresses = [];
            const idSet = new Set();
            
            res.data.forEach(address => {
              if (!idSet.has(address._id)) {
                idSet.add(address._id);
                uniqueAddresses.push(address);
              }
            });
            
            this.addressList = uniqueAddresses;
            
            // 获取默认地址或第一个地址
            const defaultAddress = this.addressList.find(item => item.isDefault);
            if (defaultAddress) {
              this.selectedAddress = defaultAddress;
            } else if (this.addressList.length > 0) {
              this.selectedAddress = this.addressList[0];
            }
          }
        },
        fail: (err) => {
          console.error('获取地址数据失败:', err);
          uni.showToast({
            title: '获取地址数据失败',
            icon: 'none'
          });
        }
      });
    },
    
    goToAddressList() {
      uni.navigateTo({
        url: '/pages/address/address-list?from=order',
        events: {
          // 监听地址选择事件
          addressSelected: (address) => {
            console.log('选择的地址:', address);
            this.selectedAddress = address;
          }
        }
      });
    },
    
    submitOrder() {
      if (!this.selectedAddress) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return;
      }
      
      if (this.productList.length === 0) {
        uni.showToast({
          title: '购物车为空',
          icon: 'none'
        });
        return;
      }
      
      // 显示确认提示框
      uni.showModal({
        title: '确认要离开收银台?',
        content: '请尽快完成支付，否则将被取消',
        cancelText: '取消订单',
        confirmText: '确认支付',
        success: (res) => {
          if (res.confirm) {
            // 生成订单数据
            const orderData = {
              _id: 'order_' + Date.now(),
              shopInfo: this.shopInfo,
              products: this.productList,
              address: this.selectedAddress,
              remark: this.remark,
              totalPrice: this.totalPrice,
              status: 'pending',
              createTime: new Date().toISOString()
            };
            
            // 保存订单数据到本地存储
            let orderList = uni.getStorageSync('orderList');
            if (orderList) {
              orderList = JSON.parse(orderList);
            } else {
              orderList = [];
            }
            
            orderList.unshift(orderData);
            uni.setStorageSync('orderList', JSON.stringify(orderList));
            
            // 跳转到支付页面
            uni.navigateTo({
              url: `/pages/order/payment?orderId=${orderData._id}`
            });
            // 在订单确认页面的提交订单成功后添加
            // 获取待移除的商品列表
            const itemsToRemove = uni.getStorageSync('itemsToRemove');
            if (itemsToRemove) {
            // 设置已完成订单的商品列表
            uni.setStorageSync('completedOrderItems', itemsToRemove);
            // 清除待移除列表
            uni.removeStorageSync('itemsToRemove');
            }
            uni.setStorageSync('orderGenerated', 'true');
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.order-confirm-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.address-section {
  display: flex;
  background-color: #fff;
  padding: 30rpx 20rpx;
  margin-top: 20rpx;
  position: relative;
  
  .address-info {
    flex: 1;
    
    .address-name-phone {
      margin-bottom: 10rpx;
      
      .name {
        font-size: 30rpx;
        font-weight: bold;
        margin-right: 20rpx;
      }
      
      .phone {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .address-detail {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .no-address {
    flex: 1;
    font-size: 30rpx;
    color: #666;
  }
  
  .address-right {
    display: flex;
    align-items: center;
  }
}

.shop-section {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 20rpx;
  
  .shop-info {
    display: flex;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    image {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }
    
    .shop-name {
      font-size: 28rpx;
      font-weight: bold;
    }
  }
  
  .product-list {
    .product-item {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      
      image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .product-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .product-name {
          font-size: 28rpx;
          color: #333;
        }
        
        .product-price-count {
          display: flex;
          justify-content: space-between;
          
          .price {
            font-size: 28rpx;
            color: #ff6b6b;
            font-weight: bold;
          }
          
          .count {
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
  }
  
  .delivery-section {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    font-size: 28rpx;
  }
}

.remark-section {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  
  text {
    font-size: 28rpx;
    margin-right: 20rpx;
  }
  
  input {
    flex: 1;
    font-size: 28rpx;
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .total-price {
    flex: 1;
    font-size: 28rpx;
    
    .price {
      font-size: 32rpx;
      color: #ff6b6b;
      font-weight: bold;
    }
  }
  
  .submit-btn {
    background-color: #0086ff;
    color: #fff;
    padding: 15rpx 40rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}
</style>